﻿//using System.Diagnostics;
//using MediatR;
//using Microsoft.AspNetCore.SignalR;
//using Microsoft.Extensions.Logging;
//using ORS.OrderRobot.IOC;
//using ORS.OrderRobot.Service.Jobs;
//using ORS.OrderRobot.ServiceContracts;
//using ORS.OrderRobot.ServiceContracts.ThridPartApi;
//using Microsoft.Extensions.DependencyInjection;
//using ORS.OrderRobot.Service.Helper;

//namespace ORS.OrderRobot.Service.Tasker
//{
//    /// <summary>
//    /// 商品是否上架探测的执行者
//    /// </summary>
//	public class ProductScanTasker : BackgroundRepeatTaskerBase, ISingleton
//    {
//        private readonly IServiceProvider _serviceProvider;
//        private readonly ILogger<ProductScanTasker> _logger;
//        private readonly IMediator _mediator;
//        private readonly IHubContext<MessageHub> _hubContext;
//        private readonly IBackgroundJobManager _backgroundJobManager;
//        private readonly LockCacheManager _lockCacheManager;
//        private readonly ISystemConfigService _systemConfigService;
//        private readonly string _msgObj = "商品扫描器";
//        public ProductScanTasker(
//            IServiceProvider serviceProvider,
//            ILogger<ProductScanTasker> logger,
//            IMediator mediator,
//            IHubContext<MessageHub> hubContext,
//            IBackgroundJobManager backgroundJobManager,
//            LockCacheManager lockCacheManager,
//            ISystemConfigService systemConfigService) :base(logger, serviceProvider)
//        {
//            _serviceProvider = serviceProvider;
//            _logger = logger;
//            _mediator = mediator;
//            _hubContext = hubContext;
//            _backgroundJobManager = backgroundJobManager;
//            _lockCacheManager = lockCacheManager;
//            _systemConfigService = systemConfigService;
//        }
//        public override string Key => "2";

//        protected override string Name => nameof(ProductScanTasker);

//        protected override async Task DoWorkAsync()
//        {
//            _logger.LogInformation("ProductScanTasker-DoWorkAsync进入");
//            var timeWatch = new Stopwatch();
//            timeWatch.Start();
//            try
//            {
//                using var scope = _serviceProvider.CreateScope();
//                var productService = scope.ServiceProvider.GetRequiredService<IThirdProductService>();
//                var configDto = await _systemConfigService.GetConfigAsync();
//                if (configDto.MointerProductTask.Disabled)
//                {
//                    _logger.LogWarning("商品扫描任务被禁用");
//                    return;
//                }
//                var productList = configDto.MointerProductInfos;
//                if (productList == null || !productList.Any())
//                {
//                    await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = $"{_msgObj} Id:{Id}", Action = "未配置目标商品" });
//                    _logger.LogError("未配置扫描的商品组");
//                    return;
//                }
//                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = $"{_msgObj} Id:{Id}", Action = "开始执行" });
//                var taskLock = await _lockCacheManager.HasScanLock();
//                if (taskLock)
//                {
//                    await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = $"{_msgObj} Id:{Id}", Action = "上一轮任务还在执行" });
//                    return;
//                }
//                await _lockCacheManager.SetScanLock();
//                var tasks = productList.Select(async p =>
//                {
//                    var result = await productService.ProductExists(p.Id);
//                    if (result)
//                    {
//                        await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = $"{p.Name}上架了" });
//                        if (configDto.MointerProductTask.AutoShopping)
//                        {
//                            await _mediator.Publish(new PurchaseEvent(p.Id, p.Name));
//                        }
//                        await _backgroundJobManager.EnqueueAsync<UpdateProductLogJob, UpdateProductLogArgs>(
//                            new UpdateProductLogArgs {
//                                ProductId = p.Id,
//                                ProductName = p.Name,
//                                CreateTime = DateTime.Now.China()
//                            }
//                        );
//                    }
//                });
//                await Task.WhenAll(tasks);
//            }
//            catch { }
//            finally
//            {
//                _logger.LogInformation("ProductScanTasker-DoWorkAsync完成");
//                timeWatch.Stop();
//                await _lockCacheManager.RemoveScanLock();
//                await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj,Action = "扫描完成", UsedTime = timeWatch.ElapsedMilliseconds});
//            }
//        }
//        /// <summary>
//        /// 执行间隔策略
//        /// </summary>
//        /// <param name="attempt"></param>
//        /// <returns></returns>
//        protected override async Task<TimeSpan> GetIntervalAsync(int attempt)
//        {
//            var configDto = await _systemConfigService.GetConfigAsync();
//            var interval = configDto.MointerProductTask.Interval;
//            var intervalUnit = configDto.MointerProductTask.IntervalUnit;
//            return intervalUnit switch
//            {
//                TimeUnit.MillionSecond => TimeSpan.FromMilliseconds(interval),
//                TimeUnit.Second => TimeSpan.FromSeconds(interval),
//                TimeUnit.Minute => TimeSpan.FromMinutes(interval),
//                _ => TimeSpan.FromSeconds(interval)
//            };
//        }
//        /// <summary>
//        /// 开始时间
//        /// </summary>
//        /// <returns></returns>
//        protected override async Task<TimeOnly> GetTargetStartTimeAsync()
//        {
//            var configDto = await _systemConfigService.GetConfigAsync();
//            return configDto.MointerProductTask.StartTime ?? new TimeOnly(06, 0);
//        }
//        /// <summary>
//        /// 是否应该停止
//        /// </summary>
//        /// <returns></returns>
//        protected override async Task<bool> ShouldStopAsync()
//        {
//            var configDto = await _systemConfigService.GetConfigAsync();
//            var endTime = configDto.MointerProductTask.EndTime ?? new TimeOnly(18,0);
//            var now = DateTime.Now.TimeOfDay;
//            return now > endTime.ToTimeSpan();
//        }
//        protected override async Task OnStartAsync()
//        {
//            await base.OnStartAsync();
//            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = "已启动" });
//        }
//        protected override async Task OnStopAsync()
//        {
//            await base.OnStopAsync();
//            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = "已停止" });
//        }
//        protected override async Task OnPauseAsync()
//        {
//            await base.OnPauseAsync();
//            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = "已暂停" });
//        }

//        protected override async Task OnResumeAsync()
//        {
//            await base.OnResumeAsync();
//            await MsgHelper.SendAsync(_hubContext, new MsgData { Obj = _msgObj, Action = "已恢复" });
//        }
//    }
//}

